package cn.rengy.web.framework.shiro.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.rengy.tpa.wxmp.oauth.OAuthManager;
import cn.rengy.tpa.wxmp.oauth.protocol.get_access_token.GetAccessTokenRequest;
import cn.rengy.tpa.wxmp.oauth.protocol.get_access_token.GetAccessTokenResponse;
import cn.rengy.tpa.wxmp.oauth.protocol.get_userinfo.GetUserinfoRequest;
import cn.rengy.tpa.wxmp.oauth.protocol.get_userinfo.GetUserinfoResponse;
import cn.rengy.web.framework.principal.WechatIdentity;
import cn.rengy.web.framework.shiro.token.WechatToken;
import cn.rengy.web.framework.sys.user.entity.UserAuth;
import cn.rengy.web.framework.wxmp.WxApp;
import cn.rengy.web.framework.wxmp.WxAppService;
import cn.rengy.web.framework.wxmp.user.WxUserPO;
import cn.rengy.web.framework.wxmp.user.WxUserService;
/**
 * 微信公众号登陆
 * @author rengy
 *
 */
@Component
public class WechatRealm extends IAuthorizingRealm{
	
	private static Logger logger = LoggerFactory.getLogger(WechatRealm.class);
	@Autowired
	private WxAppService wxAppService;
	@Autowired
	private WxUserService wxUserService;
	public WechatRealm(){
		super();
		//setAuthenticationCachingEnabled(true);//认证缓存开启
		//this.setAuthenticationCachingEnabled(true);//授权缓存开启
	}

	public boolean supports(AuthenticationToken token) {
        return token instanceof WechatToken; //仅支持WechatToken类型的Token
    }
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken){
		if (!(authenticationToken instanceof WechatToken)) {
			throw new AuthenticationException("token不匹配");
        }
		WechatToken token=(WechatToken)authenticationToken;
		String code=token.getCode();
		String appid=token.getAppid();
		WxApp app=this.wxAppService.getApp(appid);
		GetAccessTokenRequest accessTokenRequest=new GetAccessTokenRequest(code, appid, app.getAppsecret());
		//获取accessToken
		GetAccessTokenResponse accessTokenResponse=OAuthManager.getAccessToken(accessTokenRequest);
		String scope=accessTokenResponse.getScope();
		String openid=accessTokenResponse.getOpenid();
		String accessToken=accessTokenResponse.getAccess_token();
		String unionid=accessTokenResponse.getUnionid();
		WechatIdentity identity=new WechatIdentity();
		identity.setUnionid(unionid);
		identity.setOpenid(openid);
		identity.setAppid(appid);
		//查询微信用户状态
		WxUserPO wxUser =new WxUserPO();
		wxUser.setOpenid(openid);
		wxUser.setAppid(appid);
		if(OAuthManager.SCOPE_USERINFO.equals(scope)){
			GetUserinfoRequest getUserinfoRequest=new GetUserinfoRequest(accessToken,openid);
			GetUserinfoResponse getUserinfoResponse=OAuthManager.getUserinfo(getUserinfoRequest);
			wxUser.setNickname(getUserinfoResponse.getNickname());
			wxUser.setSex(getUserinfoResponse.getSex());
			wxUser.setCity(getUserinfoResponse.getCity());
			wxUser.setCountry(getUserinfoResponse.getCountry());
			//paramMap.put("privilege", getUserinfoResponse.getPrivilege());//用户特权信息，json 数组，如微信沃卡用户为（chinaunicom）
			wxUser.setProvince(getUserinfoResponse.getProvince());
			wxUser.setLanguage(getUserinfoRequest.getLang());
			wxUser.setHeadimgurl(getUserinfoResponse.getHeadimgurl());
			wxUser.setUnionid(getUserinfoResponse.getUnionid());
		}
		UserAuth userAuth=wxUserService.save(wxUser);
		if(userAuth!=null){
			identity.setWuid(userAuth.getAuth_id());
			identity.setUserid(userAuth.getUser_id());
		}
		
		return new SimpleAuthenticationInfo(identity, authenticationToken.getCredentials(), getName());	
	}
	
}
